/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.theme.service;

import com.jeeplus.cms.util.CmsCacheUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.cms.site.entity.CmsSite;
import com.jeeplus.modules.cms.site.service.CmsSiteService;
import com.jeeplus.modules.cms.theme.entity.CmsThemes;
import com.jeeplus.modules.cms.theme.mapper.CmsThemesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 主题Service
 *
 * @author Sawyer
 * @version 2020-11-21
 */
@Service
@Transactional(readOnly = true)
public class CmsThemesService extends CrudService<CmsThemesMapper, CmsThemes> {

    @Autowired
    private CmsSiteService siteService;

    @Override
    public CmsThemes get(String id) {
        return super.get(id);
    }

    @Override
    public List<CmsThemes> findList(CmsThemes cmsThemes) {
        return super.findList(cmsThemes);
    }

    @Override
    public List<CmsThemes> findAllList(CmsThemes entity) {
        return findList(entity);
    }

    @Override
    public Page<CmsThemes> findPage(Page<CmsThemes> page, CmsThemes cmsThemes) {
        return super.findPage(page, cmsThemes);
    }

    @Transactional(readOnly = false)
    @Override
    public void save(CmsThemes cmsThemes) {
        super.save(cmsThemes);
        // 清除缓存
        CmsCacheUtils.removeCache(CmsCacheUtils.THEME_LIST_CACHE);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(CmsThemes cmsThemes) {
        // 判断主题是否被关联
        CmsSite site = new CmsSite();
        site.setTheme(cmsThemes);
        List<CmsSite> cmsSiteList = siteService.findList(site);
        if (null != cmsSiteList && cmsSiteList.size() > 0) {
            throw new RuntimeException(String.format("主题[%s]已被站点[%s]使用", cmsThemes.getId(), cmsSiteList.get(0).getName()));
        }
        super.delete(cmsThemes);
        // 清除缓存
        CmsCacheUtils.removeCache(CmsCacheUtils.THEME_LIST_CACHE);
    }

    /**
     * 根据siteId获取对应的主题
     *
     * @param siteId 网站id
     * @return CmsTheme or null
     */
    public CmsThemes findThemeBySiteId(final String siteId) {
        return mapper.findThemeBySiteId(siteId);
    }
}
